package com.guyaogg.gulimall.ware.listener;

import com.guyaogg.common.to.mq.OrderTo;
import com.guyaogg.common.to.mq.StockLockedTo;
import com.guyaogg.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 顾遥
 */
@Slf4j
@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void handlerOrderCloseRelease(OrderTo to, Message message, Channel channel) throws IOException {
        log.debug("订单关闭，准备解锁库存");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            log.warn("解锁订单发生错误：{}",e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
    /**
     * 库存自动解锁
     *
     * 1）下订单成功，订单过期没有支付自动解锁；被用户手动取消。都要解锁库存
     * 2）下订单成功，库存锁定成功，接下来的业务调用失败。导致订单回滚。
     *           之后自动解锁
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {

        log.debug("收到解锁消息...");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.warn("解锁订单发生错误：{}",e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }


    }
}
